//
//  WKWebScene.swift
//  WebViewWithJSDemo
//
//  Created by 李明明 on 16/1/9.
//  Copyright © 2016年 李明明. All rights reserved.
//

import UIKit
import WebKit

class WKWebScene: UIViewController, WKNavigationDelegate {

    var web: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        web = WKWebView(frame: CGRect.zero, configuration: Configuration())
        web.navigationDelegate = self
        let request = URLRequest(url: URL(fileURLWithPath: urlStr!))
        web.load(request)
        web.translatesAutoresizingMaskIntoConstraints = false
        let contraints = addConstraint()
        view.addSubview(web)
        NSLayoutConstraint.activate(contraints)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(WKWebScene.pop), name: NSNotification.Name(rawValue: popNoti), object: nil)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - noti
    func pop() {
        navigationController?.popViewController(animated: true)
    }
    // MARK: - webview delegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let style = String(format: "myfunction('%@')", NSStringFromClass(webView.classForCoder))
        webView.evaluateJavaScript(style, completionHandler: nil)
        webView.evaluateJavaScript("document.body.style.zoom=2", completionHandler: nil)
    }
    
    // MARK: - constraint
    func addConstraint()->[NSLayoutConstraint] {
        let top = NSLayoutConstraint(item: web, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0)
        let left = NSLayoutConstraint(item: web, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0)
        let bottom = NSLayoutConstraint(item: web, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0)
        let right = NSLayoutConstraint(item: web, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: 0)
        return [top, left, bottom, right]
    }

}
